package besta.moon.command;

import java.io.*;

import besta.moon.statement.MoonStatement;
import besta.moon.sql.parser.SQLTokenizer;
import besta.moon.MoonException;
import besta.moon.MoonConnection;
import besta.moon.MoonCode;
import besta.moon.MoonLogger;
import besta.moon.MoonCommand;
import besta.moon.engine.Database;
import besta.moon.util.MoonUtils;

public class CommandDrop extends MoonCommand {

    public CommandDrop(MoonLogger log, String catalog, String name, int type) {
        super(log);
        this.type = type;
        this.catalog = catalog;
        this.name = name;
    }

    @Override
    public void executeImpl(MoonConnection con, MoonStatement st) throws Exception {
        switch (type) {
            case SQLTokenizer.DATABASE -> {
                if (name.startsWith("file:")) {
                    name = name.substring(5);
                }
                File dir = new File(name);
                if (!dir.isDirectory() || !new File(dir, MoonUtils.MASTER_FILENAME).exists()) {
                    throw MoonException.create(MoonCode.DB_NONEXISTENT, name);
                }
                File files[] = dir.listFiles();
                if (files != null) {
                    for (int i = 0; i < files.length; i++) {
                        files[i].delete();
                    }
                }
                dir.delete();
            }
            case SQLTokenizer.TABLE -> Database.dropTable(con, catalog, name);
            case SQLTokenizer.VIEW -> Database.dropView(con, catalog, name);
            case SQLTokenizer.INDEX, SQLTokenizer.PROCEDURE -> throw new java.lang.UnsupportedOperationException();
            default -> throw new Error();
        }
    }
}
